package com.cfk.bookmarkdirectory.util;

import com.cfk.bookmarkdirectory.config.BookmarkDirectoryState;
import com.cfk.bookmarkdirectory.model.BookmarkNode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.lang.reflect.Type;
import java.util.List;

/**
 * author 3156056300@qq.com
 */
public class BookmarkDirectoryUtil {
    private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();

    public static void exportToJson(List<BookmarkDirectoryState.BookmarkNodeState> bookmarks, File file) throws IOException {
        try (Writer writer = new FileWriter(file)) {
            gson.toJson(bookmarks, writer);
        }
    }

    public static List<BookmarkDirectoryState.BookmarkNodeState> importFromJson(File file) throws IOException {
        try (Reader reader = new FileReader(file)) {
            Type type = new TypeToken<List<BookmarkDirectoryState.BookmarkNodeState>>(){}.getType();
            return gson.fromJson(reader, type);
        }
    }

    public static BookmarkNode convertToNode(BookmarkDirectoryState.BookmarkNodeState state) {
        BookmarkNode node = new BookmarkNode(state.name, state.directoryPath, state.isDirectory);
        
        for (BookmarkDirectoryState.BookmarkNodeState child : state.children) {
            node.add(convertToNode(child));
        }
        
        return node;
    }
}